package com.example.esdemo.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.esdemo.mapper.PostionMapper;
import com.example.esdemo.pojo.Position;
import org.elasticsearch.action.LatchedActionListener;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Authther: mrwu
 * @date:2021/5/18-05
 * @Description:com.example.esdemo.service
 */
@Service
public class PostionServiceImpl extends ServiceImpl<PostionMapper, Position> implements PostionService {
    //注入es操作客户端
    @Autowired
    RestHighLevelClient restHighLevelClient;


    @Override
    public void importes() {
        //可分页查询
        List<Position> positions = baseMapper.selectList(null);

        //导入es
        //批处理
        BulkRequest bulkRequest = new BulkRequest();
        //设置导入超时时长
        for (Position position : positions) {
            IndexRequest indexRequest = new IndexRequest("lagou_position").id(position.getId()).source(JSON.toJSONString(position), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println(bulk.status());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
